#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

// 存钱
void Deposit(mutex& m, int& money)
{
	// 1.锁的粒度尽可能的最小化
	for (int i = 0; i < 100; i++)
	{
		m.lock();
		money += 1;
		m.unlock();
	}
}

// 取钱
void Withdraw(mutex& m, int& money)
{
	for (int i = 0; i < 100; i++)
	{
		m.lock();
		money -= 2;
		m.unlock();
	}
}

int main()
{
	int money = 2000;
	mutex m;

	cout << "Current money: " << money << endl;

	thread t1(Deposit, ref(m), ref(money));
	thread t2(Withdraw, ref(m), ref(money));

	t1.join();
	t2.join();

	cout << "Final money: " << money << endl;

	return 0;
}